package com.xhai.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhai.common.domain.ResponseResult;
import com.xhai.common.domain.entity.SysUser;
import com.xhai.common.domain.page.PageResponseEntity;
import com.xhai.common.utils.BeanUtils;
import com.xhai.common.utils.SecurityUtils;
import com.xhai.common.utils.classes.StringUtils;
import com.xhai.domain.user.request.UserAddForm;
import com.xhai.domain.user.request.UserPageQueryForm;
import com.xhai.domain.user.response.UserPageVo;
import com.xhai.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author xhai
 * @since 2025-05-24
 */
@RestController
@RequestMapping("/sysUser")
@Slf4j
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    /**
     * 分页查询系统用户
     *
     * @param form 分页查询系统用户查询表单
     * @return 分页查询结果
     */
    @PostMapping("/page")
    @Operation(summary = "分页查询系统用户", description = "分页查询系统用户")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "400", description = "查询失败"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "form", description = "分页查询系统用户查询表单", schema = @Schema(implementation = UserPageQueryForm.class)),
    })
    public ResponseResult<PageResponseEntity<UserPageVo>> page(@RequestBody UserPageQueryForm form) {

        // 先分页查询出用户实体
        Page<SysUser> page = new Page<>(form.getCurrentPage(), form.getPageSize());
        // 构造查询条件
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(form.getUsername()), SysUser::getUsername, form.getUsername())
                .eq(StringUtils.isNotBlank(form.getType()), SysUser::getType, form.getType())
                .eq(StringUtils.isNotBlank(form.getPhone()), SysUser::getPhone, form.getPhone())
                .like(StringUtils.isNotBlank(form.getNickname()), SysUser::getNickname, form.getNickname())
                .eq(StringUtils.isNotBlank(form.getRealName()), SysUser::getRealName, form.getRealName());
        // 查询
        Page<SysUser> pageQueryResult = sysUserService.page(page, queryWrapper);

        // 转换成响应实体
        List<UserPageVo> userPageVos = pageQueryResult.getRecords().stream().map(user -> {
            UserPageVo userPageVo = new UserPageVo();
            BeanUtils.copyProperties(user, userPageVo);
            return userPageVo;
        }).toList();
        // 构造分页响应实体
        PageResponseEntity<UserPageVo> pageResponseEntity = new PageResponseEntity<>(userPageVos, pageQueryResult.getTotal(), pageQueryResult.getCurrent(), pageQueryResult.getSize());

        return ResponseResult.success(pageResponseEntity);
    }

    @PostMapping("/add")
    @Operation(summary = "新增系统用户", description = "新增系统用户")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "新增成功"),
            @ApiResponse(responseCode = "400", description = "新增失败"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @Parameters({
            @Parameter(name = "form", description = "新增系统用户表单", schema = @Schema(implementation = UserAddForm.class)),
    })
    public ResponseResult<?> add(@Validated @RequestBody UserAddForm form) {
        SysUser user = new SysUser();
        BeanUtils.copyProperties(form, user);

        // 校验新增用户信息
        if (!sysUserService.checkUserNameUnique(user)) {
            return ResponseResult.fail("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotBlank(user.getPhone()) && !sysUserService.checkPhoneUnique(user)) {
            return ResponseResult.fail("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotBlank(user.getPassword()) && !sysUserService.checkPasswordValid(user)) {
            return ResponseResult.fail("新增用户'" + user.getUsername() + "'失败，密码无效");
        }

        // 设置创建时间、创建人、更新时间、更新人、逻辑删除标识、版本号
        // 自动设置

        // 设置加密盐
        user.setEncryptSalt(user.getUsername());

        // todo 加密盐没用上 设置密码
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));

        return ResponseResult.success(sysUserService.insertUser(user, form.getDeptIds(), form.getPostIds()));
    }
}
